
package com.android.replace;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {
    public static String replaceAllSymbol(String str) {
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static String replaceAllTab(String str) {
        Pattern CRLF = Pattern.compile("(\r)");
        Matcher m = CRLF.matcher(str);
        return str.replaceAll("\\\\r", "").trim();
    }

    /**
     * 判断字符串的编码
     *
     * @param str
     * @return
     */
    public static String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s = encode;
                return s;
            }
        } catch (Exception exception) {
        }
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return "";
    }

    public static byte[] getUTF8BytesFromGBKString(String gbkStr) {
        int n = gbkStr.length();
        byte[] utfBytes = new byte[3 * n];
        int k = 0;
        for (int i = 0; i < n; i++) {
            int m = gbkStr.charAt(i);
            if (m < 128 && m >= 0) {
                utfBytes[k++] = (byte) m;
                continue;
            }
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));
        }
        if (k < utfBytes.length) {
            byte[] tmp = new byte[k];
            System.arraycopy(utfBytes, 0, tmp, 0, k);
            return tmp;
        }
        return utfBytes;
    }

    private static void encode(File file, String targetEncode) {
        File destFile = new File(file.getAbsolutePath() + ".tmp");
        File sourceFile = new File(file.getAbsolutePath());
        BufferedReader br = null;
        BufferedWriter bw = null;
        boolean success = false;
        try {
            bw = new BufferedWriter(new FileWriter(destFile));
            br = new BufferedReader(new FileReader(sourceFile));
            String line;
            String encode = null;
            while ((line = br.readLine()) != null) {
                if (encode == null) {
                    encode = getEncoding(line);
                }
                String target = new String(getUTF8BytesFromGBKString(line), targetEncode);
                bw.write(target + "\r");
            }
            success = true;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            success = false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            success = false;
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (success) {
                sourceFile.delete();
                destFile.renameTo(sourceFile);
            }
        }

    }

    public static void decodeString(String dir, String targetEncode) {
        if (dir == null || targetEncode == null) {
            return;
        }
        File dirFile = new File(dir);
        if (!dirFile.isDirectory()) {
            return;
        }
        File[] listFiles = dirFile.listFiles();
        Iterator<File> iterator = Arrays.asList(listFiles).iterator();
        while (iterator.hasNext()) {
            File file = (File) iterator.next();
            if (file.isDirectory()) {
                File[] files = dirFile.listFiles();
                Iterator<File> subInterator = Arrays.asList(files).iterator();
                while (subInterator.hasNext()) {
                    File subFile = (File) subInterator.next();
                    encode(subFile, targetEncode);
                }
            } else {
                encode(file, targetEncode);
            }
        }
    }
}
